package com.hmall.trade.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.common.constant.MQConstant;
import com.hmall.trade.domain.dto.OrderCheckMsgDto;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OrderPayStatusCheckListener {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.ORDER_CHECK_QUEUE),
            exchange = @Exchange(name = MQConstant.ORDER_CHECK_TOPIC, type = ExchangeTypes.DIRECT, delayed = "true"),
            key = MQConstant.ORDER_CHECK_KEY
    ))
    public void onOrderPayStatusCheckMsg(String msg) {
        log.info("onOrderPayStatusCheckMsg msg:{}", msg);
        OrderCheckMsgDto orderCheckMsgDto = JSONUtil.toBean(msg, OrderCheckMsgDto.class);
        // 先判断订单状态
        Order orderDB = orderService.getById(orderCheckMsgDto.getOrderId());
        if (orderDB == null) {
            log.error("订单不存在，msg：{}", msg);
            return;
        }
        // 如果说 已经支付了，返回
        Integer status = orderDB.getStatus();
        if (status != null && status > 1) {
            log.info("订单：{} 状状态是：{}，无需进一步处理", orderCheckMsgDto.getOrderId(), status);
            return;
        }
        // 如果说 没有支付
        // 判断还有剩余的过期时间
        if (orderCheckMsgDto.hasNextMill()) {
            Integer nextMill = orderCheckMsgDto.getNextMill();
            // 如果还有剩余时间，继续发送延迟消息
            rabbitTemplate.convertAndSend(MQConstant.ORDER_CHECK_TOPIC, MQConstant.ORDER_CHECK_KEY, JSONUtil.toJsonStr(orderCheckMsgDto), new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setHeader("x-delay", nextMill);
                    log.info("发送延迟{}的消息", nextMill);
                    return message;
                }
            });
        } else {
            // 如果没有，取消订单 TODO
            log.info("取消订单：{}", orderCheckMsgDto.getOrderId());
        }
    }
}